<?php

namespace App\Http\Controllers\api;

use Laravel\Passport\Passport;
use Laravel\Passport\Token;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Response;

class UserController extends AppBaseController
{
    use  AuthenticatesUsers;

    public function __construct()
    {
        $this->content = array();
        $this->clientId = config('custom.client_id');
    }


    /**
     * 用户登录
     *
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $this->validate($request, ['name' => 'required', 'password' => 'required']);

        //验证账号密码
        $isLogin = Auth::guard('web')->attempt(['name' => request('name'), 'password' => request('password')]);

        if ($isLogin) {
            $user = Auth::guard('web')->user();
            if($user->flag == 1){
                return $this->sendError('账号已被冻结，请咨询管理员', 403);
            }
            Passport::personalAccessClient($this->clientId);

            //生成token
            Token::where('user_id', $user->id)->where('client_id', $this->clientId)->delete();

            //构建返回数据
            $data = [];
            $data['token'] = 'Bearer ' . $user->createToken($user->name)->accessToken;
            return $this->sendResponse($data, '登录成功');
        }

        return $this->sendError('用户名或密码不正确', 403);
    }

    /**
     * 删除token并注销
     *
     * @param Request $request
     * @return mixed
     */
    public function logout(Request $request)
    {
        $user = Auth::user();

        Token::where('user_id', $user->id)->where('client_id', $this->clientId)->delete();

        return $this->sendResponse([], '退出成功');
    }
}